package com.example.exp3demo.controller;

import com.example.exp3demo.model.ConfirmedCase;
import com.example.exp3demo.service.ConfirmedService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class ConfirmedController {
    private ConfirmedService confirmedService;

    public ConfirmedController(ConfirmedService confirmedService) {
        this.confirmedService = confirmedService;
    }

    @GetMapping("/{country}")
    public String show(Model model, @PathVariable("country") String country) {
        List<ConfirmedCase> confirmed;

        if (country == null || country.equals("全球"))
            confirmed = confirmedService.getConfirmedCaseList();

        else
            confirmed = confirmedService.getConfirmedCaseList()
                    .parallelStream()
                    .filter(locationStates -> locationStates.getCountry().equals(country))
                    .collect(Collectors.toUnmodifiableList());

        model.addAttribute("country", country);

        //统计所有确诊总数
        int totalReportedCases=confirmed.parallelStream().mapToInt(ConfirmedCase::getLatestTotalCases).sum();
        //统计相较于前一天增加的确诊病例数
        int totalNewCases=confirmed.parallelStream().mapToInt(ConfirmedCase::getIncreaseCases).sum();

        model.addAttribute("confirmedCase",confirmed);
        model.addAttribute("totalReportedCases",totalReportedCases);
        model.addAttribute("totalNewCases",totalNewCases);
        model.addAttribute("localDateTime", LocalDateTime.now());
        return "index";
    }

}
